package com.study.mynew.ui;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.study.mynew.R;
import com.study.mynew.adapter.NewItemAdapter;
import com.study.mynew.bean.NewItemBean;

import org.litepal.LitePal;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class HistoryActivity extends BaseActivity {

    private RecyclerView rv_history;
    private ImageButton delete_btn,back_btn;
    private NewItemAdapter mAdapter ;
    @Override
    public int initView() {
        return R.layout.activity_history;
    }

    public HistoryActivity() {}

    @Override
    public void initData() {
        rv_history = findViewById(R.id.history_news);
        delete_btn = findViewById(R.id.delete_btn);
        back_btn = findViewById(R.id.BackBtn);
        mAdapter = new NewItemAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_history.setLayoutManager(linearLayoutManager);
        rv_history.setAdapter(mAdapter);
        initHistory();
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                NewItemBean item = mAdapter.getItem(position);
                Intent intent = new Intent(HistoryActivity.this, NewsActivity.class);
                intent.putExtra(NewsActivity.EXTRA_DATA, item);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initListener() {
        delete_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LitePal.deleteAll(NewItemBean.class, "fromCollection=?", "0");
                initHistory(); //加载历史记录
                Toast.makeText(HistoryActivity.this, "清空收藏夹！", Toast.LENGTH_SHORT).show();
            }
        });
        back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initHistory() {
        List<NewItemBean> newItemBeans = LitePal.where("fromCollection=?", "0").find(NewItemBean.class);
        mAdapter.setNewInstance(newItemBeans);

    }
    @Override
    public void onResume() {
        super.onResume();
        initHistory();
    }

}